import { codeKeyLogin } from '@/services/cas';
import { Login as chdact2Login } from '@/services/chdact2';
import { Login } from '@/services/chdstore';
import { Login as chdtuanLogin } from '@/services/chdtuan';
import { Flex, Image, Modal } from 'antd';
import { useEffect, useRef } from 'react';

export default () => {
  const timerRef = useRef<any>(null);

  timerRef.current = setInterval(() => {
    codeKeyLogin().then((res) => {
      console.log(res, 'codeKeyLogin');
      const loginMap = {
        'chd-grade/': chdact2Login,
        'shop/': Login,
        'group-buying/': chdtuanLogin,
      };
      const path = Object.keys(loginMap).find((path) => {
        if (location.href.includes(path)) {
          return true;
        }
        return false;
      });
      console.log(loginMap[path]);
      if (!res?.data?.failReason) {
        if (timerRef.current) {
          clearInterval(timerRef.current);
        }

        loginMap[path]?.(res?.data?.ticket).then(() => {
          Modal.destroyAll();
          history.go(0);
        });
      }
    });
  }, 3000);

  useEffect(() => {
    return () => {
      if (timerRef.current) {
        clearInterval(timerRef.current);
      }
    };
  });

  return (
    <Flex justify="center">
      <Image src="http://localhost:3000/cas/authen/getcodekey.jsonp?maxsize=145&appId=991000350&areaId=1&r=0.5138153108257164" />
    </Flex>
  );
};
